﻿using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.Windows.Controls;
using TruckScale.Helpers;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public class DBRestoreViewModel : ViewModelBase
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public string InfoBar { get; set; }
    public string RestoreFilePath { get; set; }
    public DelegateCommand LoadFileCommand { get; private set; }
    public DelegateCommand RestoreCommand { get; private set; }
    public DBRestoreViewModel()
    {
      LoadFileCommand = new DelegateCommand(OnLoadFileExecuted);
      RestoreCommand = new DelegateCommand(OnRestoreExecuted);
    }

    private void OnLoadFileExecuted(object obj)
    {
      CommonOpenFileDialog dialog = new CommonOpenFileDialog
      {
        InitialDirectory = Global._weighConfig["BackupPath"],
        IsFolderPicker = false
      };
      if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
      {
        RestoreFilePath = dialog.FileName;
      }
    }

    private void OnRestoreExecuted(object obj)
    {
      try
      {
        InfoBar = "正在恢复...";

        string cnnstr = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
        var cnnDictionary = DBHelper.ParseConnectionString(cnnstr);

        // 检查 RestoreFilePath 文件是否存在
        if (!File.Exists(RestoreFilePath))
        {
          InfoBar = "请选择数据库文件";
          return;  // 退出方法，避免执行错误的命令
        }

        string command = $@"mysql -h{cnnDictionary["Data Source"]} -P{cnnDictionary["port"]} -u{cnnDictionary["userid"]} -p{cnnDictionary["password"]} {cnnDictionary["initial catalog"]}< ""{RestoreFilePath}""";

        SetLog($"执行恢复命令：{command}", LogType.OperationLogger, LogLevel.Debug);

        // 执行备份命令
        ExecuteCommand(command);

        InfoBar = "恢复完成";
      }
      catch (Exception ex)
      {
        InfoBar = "恢复失败，请查看操作日志";
        SetLog($"恢复失败：{ex.Message}", LogType.OperationLogger, LogLevel.Error);
      }

    }

    // 执行命令行命令
    static void ExecuteCommand(string command)
    {
      ProcessStartInfo processInfo = new ProcessStartInfo
      {
        FileName = "cmd.exe",
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true, // 捕获错误输出
        UseShellExecute = false,
        CreateNoWindow = true
      };

      Process process = new Process
      {
        StartInfo = processInfo
      };
      process.Start();

      process.StandardInput.WriteLine(command);
      process.StandardInput.Flush();
      process.StandardInput.Close();

      // 读取标准输出并打印
      string output = process.StandardOutput.ReadToEnd();
      Console.WriteLine(output);

      // 读取标准错误并打印（如果有错误的话）
      string errorOutput = process.StandardError.ReadToEnd();
      if (!string.IsNullOrEmpty(errorOutput))
      {
        Console.WriteLine(errorOutput);
      }

      process.WaitForExit();
    }
  }
}
